import { Form, Input } from 'antd-mobile'
import styles from './index.module.less'
import { useEffect, useState } from 'react'
import FormPicker from '@/components/FormComponets/FormPicker'
import { AddCircleOutline } from 'antd-mobile-icons'
import arrow_down from '@/resource/arrow_down.png'
import { observer, useLocalObservable } from 'mobx-react'
import Store from '../store'
import BtnBotLayout from '@/components/BtnBotLayout'
import InputLimit from '@/components/InputLimit'
import { scrollToById } from '@/utils'
import { useLocation, useParams } from 'umi'
import { toJS } from 'mobx'

const maxAge = 100
/** 默认初始年龄列表 */
let ageArr: any[] = []
for (let i = 0; i <= maxAge; i++) {
    ageArr.push({ label: `${i}岁`, value: `${i}` })
}

/** 默认角色名称 */
const roleNameList = ['子女', '学生', '休闲者', '公民', '工作者', '持家者']

export default observer(() => {
    const store = useLocalObservable(() => Store())
    const { stepData, nextStep, getRainbowDetail } = store
    const [form] = Form.useForm()
    const [errInfo, setErrorInfo] = useState<any>({}) /** 错误下标 */
    const { from } = useLocation().query
    const { id } = useParams<any>()

    /** 下一步 */
    const handleNext = () => {
        form.validateFields()
            .then((values: any) => {
                // 判断是否修改过
                const { data } = values
                const temp = data.map((item: any, idx: number) => {
                    const isTouch = form.isFieldsTouched([
                        ['data', idx, 'name'],
                        ['data', idx, 'age_start'],
                        ['data', idx, 'age_end'],
                    ])
                    console.log(isTouch)
                    if (isTouch) {
                        return {
                            ...item,
                            settings: undefined,
                        }
                    }
                    return item
                })

                nextStep({ data: temp })
            })
            .catch(err => {
                /** 错误提示 */
                const { errorFields = [] } = err || {}
                let errIndex: any = {}
                errorFields.forEach((item: any, idx: number) => {
                    const { name, errors } = item
                    if (errors.length) {
                        errIndex[name['1']] = 1
                    }
                    if (idx === 0) {
                        scrollToById(document.getElementsByClassName('content_wrappper')[0] as HTMLElement, `data_${name['1']}`)
                    }
                })
                setErrorInfo(errIndex)
                return Promise.reject(err)
            })
    }

    useEffect(() => {
        form.resetFields()
    }, [stepData])
    useEffect(() => {
        document.title = '生涯彩虹图'
        if (from !== 'step2') {
            getRainbowDetail()
        }
    }, [])

    return (
        <div className={styles.outside}>
            <BtnBotLayout
                footer={
                    <div className={styles.blue_btn} onClick={handleNext}>
                        下一步
                    </div>
                }
            >
                <div className={styles.step_tips}>请思考你的一生可能有那些角色，每个角色从哪个阶段出现，延续到哪个阶段，思考每个角色你会投入的程度。根据彩虹模板，完成属于你自己的生涯彩虹图</div>
                {id && (
                    <div className={styles.form_wrapper}>
                        <div className={styles.container}>
                            <Form
                                form={form}
                                layout="horizontal"
                                initialValues={{
                                    data: stepData.length > 0 ? stepData : [{ name: '子女' }],
                                }}
                            >
                                <Form.Array name="data">
                                    {(fields, { remove, add }) =>
                                        fields.map(({ index }, idx) => (
                                            <>
                                                {idx === 0 && (
                                                    <div className={styles.title}>
                                                        <span className={styles.title_span}>
                                                            第一步：设置角色
                                                            <span className={styles.num_wrapper}>
                                                                （<span className={fields.length ? styles.num : ''}>{fields.length}</span>
                                                                /6）
                                                            </span>
                                                        </span>
                                                    </div>
                                                )}
                                                <div className={styles.block} id={`data_${index}`}>
                                                    {!!index && <div className={styles.del_icon} onClick={() => remove(index)} />}
                                                    <div className={styles.block_title}>角色{index + 1}</div>
                                                    <div className={styles.form_item_wrapper}>
                                                        <div className={styles.form_label}>角色名称</div>

                                                        <div className={styles.form_content}>
                                                            <Form.Item name={[index, 'name']} label="角色名称" rules={[{ required: true }]} noStyle>
                                                                <InputLimit disabled regExp={/^[a-zA-Z\u4e00-\u9fa5]+$/} maxLength={10} placeholder={`请输入角色名称，如：${roleNameList[index]}`} />
                                                            </Form.Item>
                                                        </div>
                                                    </div>
                                                    <div className={styles.form_item_wrapper}>
                                                        <div className={styles.form_label}>开始年龄</div>
                                                        <div className={styles.form_content}>
                                                            <Form.Subscribe to={[['data', index, 'age_end']]}>
                                                                {field => {
                                                                    const { data } = field
                                                                    const { age_end } = data[index]
                                                                    const col = ageArr.slice(0, Number(age_end?.[0] || maxAge))
                                                                    return (
                                                                        <Form.Item name={[index, 'age_start']} rules={[{ required: true }]} trigger="onConfirm" noStyle>
                                                                            <FormPicker
                                                                                placeholder="请选择角色开始的年龄"
                                                                                rightIcon={<img className={styles.arrow} src={arrow_down} />}
                                                                                columns={[col]}
                                                                            />
                                                                        </Form.Item>
                                                                    )
                                                                }}
                                                            </Form.Subscribe>
                                                        </div>
                                                    </div>
                                                    <div className={styles.form_item_wrapper}>
                                                        <div className={styles.form_label}>结束年龄</div>
                                                        <div className={styles.form_content}>
                                                            <Form.Subscribe to={[['data', index, 'age_start']]}>
                                                                {field => {
                                                                    const { data } = field
                                                                    const { age_start } = data[index]
                                                                    const col = ageArr.slice(Number(age_start?.[0] || 0))
                                                                    return (
                                                                        <Form.Item name={[index, 'age_end']} rules={[{ required: true }]} trigger="onConfirm" noStyle>
                                                                            <FormPicker
                                                                                placeholder="请选择角色结束的年龄"
                                                                                rightIcon={<img className={styles.arrow} src={arrow_down} />}
                                                                                columns={[col]}
                                                                            />
                                                                        </Form.Item>
                                                                    )
                                                                }}
                                                            </Form.Subscribe>
                                                        </div>
                                                    </div>
                                                    <div
                                                        style={{
                                                            display: errInfo[index] ? 'block' : 'none',
                                                        }}
                                                        className={styles.err_info}
                                                    >
                                                        请填写完整角色信息
                                                    </div>
                                                </div>
                                                {fields.length - 1 === idx && fields.length < 6 && (
                                                    <div className={styles.options_wrapper}>
                                                        <span
                                                            className={styles.add_wrapper}
                                                            onClick={() => {
                                                                const values = form.getFieldsValue()
                                                                const newArr = roleNameList.filter(el => {
                                                                    const flag = values.data.find((item: any) => item.name === el)
                                                                    return !flag ? true : false
                                                                })
                                                                add({ name: newArr[0] })
                                                            }}
                                                        >
                                                            <AddCircleOutline />
                                                            添加角色
                                                        </span>
                                                    </div>
                                                )}
                                            </>
                                        ))
                                    }
                                </Form.Array>
                            </Form>
                        </div>
                    </div>
                )}
            </BtnBotLayout>
        </div>
    )
})
